package com.wk.net.heartbeat.handler.listeners.console;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import com.wk.net.heartbeat.HeartbeatTransferer;
import com.wk.net.heartbeat.handler.HeartbeatListener;
import com.wk.net.heartbeat.handler.HeartbeatObserver;
import com.wk.net.heartbeat.handler.ParsedHeartbeatMessage;

public class ConsoleHeartbeatListener<HeartbeatType> implements HeartbeatListener<HeartbeatType> {
	public ConsoleHeartbeatListener(HeartbeatTransferer<HeartbeatType> transferer) {
		this.transferer = transferer;
	}

	@Override
	public void onHeartbeat(ParsedHeartbeatMessage<HeartbeatType> message) {
		ByteArrayOutputStream content = new ByteArrayOutputStream();
		try {
			transferer.send(message.heartbeat, content);
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("[收到心跳]来源：" + message.source + "；已监视？" + message.isSourceObserved + "；内容："
				+ new String(content.toByteArray()));
	}

	@Override
	public void alterObservation(ParsedHeartbeatMessage<HeartbeatType> message, HeartbeatObserver observer) {
		if (!message.isSourceObserved) {
			synchronized (observer) {
				observer.observe(message.source, true);
			}
		}
	}

	private HeartbeatTransferer<HeartbeatType> transferer;
}
